package com.yykj.common.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Created by chendg on 2020/9/4 0004.
 */
@Configuration
@EnableSwagger2
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig extends WebMvcConfigurationSupport {

	@Value("${spring.profiles.active}")
	public String active;

	@Value("${spring.application.name}")
	public String serviceName;

	@Bean
	public Docket createRestApi() {

		return new Docket(DocumentationType.SWAGGER_2)
				.enable(active.equalsIgnoreCase("local")
						|| active.equalsIgnoreCase("dev")
						|| active.equalsIgnoreCase("test")
						|| active.equalsIgnoreCase("cdg") )// 是否开启swagger
				.apiInfo(apiInfo()).select()
				.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))// 只扫描有@Api注解的类
//				 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//只扫描有@ApiOperation的方法
				// .apis(RequestHandlerSelectors.basePackage("com.yykj.hospital.server.controller"))//扫描包
				.paths(PathSelectors.any()).build();
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title(serviceName + " api接口")// 标题
				.description(serviceName + " api接口")// 描述
				.termsOfServiceUrl("")// 服务地址
				.contact(new Contact("", "", ""))// 联系方式
				.version("1.0.0")// 版本号
				.build();
	}

	@Override
	protected void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("forward:/index.html");
		// registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
	}

	@Override
	protected void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("doc.html")
				.addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**")
				.addResourceLocations("classpath:/META-INF/resources/webjars/");
	}

}
